package com.eystar.pdc.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.eystar.ext.kit.ContainerKit;
import com.eystar.ext.kit.tree.BaseTree;
import com.eystar.ext.kit.tree.TreeKit;

@SuppressWarnings("unchecked")
public class ResourceTree {

	public final static ResourceTree dao = new ResourceTree();
	
	/**
	 * 列出所有资源，以对象集合的形式返回
	 * @param forceRefresh 是否更新缓存记录
	 * @return
	 */
	public List<BaseTree> listResource(boolean forceRefresh) {
		if (!ContainerKit.contains("resources") || forceRefresh) {
			// 1、查找所有的菜单
			List<Resource> resources = Resource.dao.findAll();
			List<BaseTree> trees = new ArrayList<BaseTree>();
			for (Resource resource : resources) {
				trees.add(resource.toBaseTree());
			}
			ContainerKit.put("resources", trees);
		}
		return (List<BaseTree>) ContainerKit.get("resources");
	}
	
	/**
	 * 列出所有资源，以Map<menu_remark,BaseTree>形式返回
	 * @param forceRefresh 是否更新缓存记录
	 * @return
	 */
	public Map<String, BaseTree> listResourceMap(boolean forceRefresh){
		if (!ContainerKit.contains("resource_map") || forceRefresh) {
			Map<String, BaseTree> map = new HashMap<String, BaseTree>();
			for (BaseTree resource : listResource(false)) {
				map.put((String) resource.getAttr("menu_remark"), resource);
			}
			ContainerKit.put("resource_map", map);
		}
		return (Map<String, BaseTree>) ContainerKit.get("resource_map");
	}
	
	/**
	 * 列出所有资源，以树形BaseTree形式返回
	 * @param forceRefresh 是否更新缓存记录
	 * @return
	 */
	public List<BaseTree> listResourceTree(boolean forceRefresh) {
		if (!ContainerKit.contains("resource_tree") || forceRefresh) {
			List<BaseTree> grids = listResource(false);
			List<BaseTree> tree = TreeKit.getChildTreeObjects(grids, "0");
			ContainerKit.put("resource_tree", tree);
		}
		return (List<BaseTree>) ContainerKit.get("resource_tree");
	}
	
	/**
	 * 列出所有资源，以树形结果JSON返回
	 * @param forceRefresh 是否更新缓存记录
	 * @return
	 */
	public String listResourceTreeJson(boolean forceRefresh) {
		if (!ContainerKit.contains("resource_json") || forceRefresh) {
			List<BaseTree> trees = listResourceTree(false);
			BaseTree root = new BaseTree("0","-1","资源列表");
			root.setChildren(trees);
			JSONArray array = new JSONArray();
			array.add(root);
			ContainerKit.put("resource_json", JSONArray.toJSONString(array));
		}
		return (String) ContainerKit.get("resource_json");
	}
}
